  <?php

  class aoiPaymentIpnAction extends sfAction
  {
    public function execute($request)
    {
      $this->setLayout(false);
      // create our logger object

      $p = new paypal_class();
      $p->ipn_log = new sfFileLogger(new sfEventDispatcher(), array('file' => sfConfig::get('sf_log_dir') . '/paypal_ipn.log'));
      if ($p->validate_ipn())
      {
         // Payment has been recieved and IPN is verified.  This is where you
         // update your database to activate or process the order, or setup
         // the database with the user's order details, email an administrator,
         // etc.  You can access a slew of information via the ipn_data() array.
  
         // Check the paypal documentation for specifics on what information
         // is available in the IPN POST variables.  Basically, all the POST vars
         // which paypal sends, which we send back for validation, are now stored
         // in the ipn_data() array.

         // For this example, we'll just email ourselves ALL the data.
         $subject = 'Instant Payment Notification - Recieved Payment';
         $p->send_report($subject);
      }
      else
      {
         $subject = 'Instant Payment Notification - Payment Fail';
         $p->send_report($subject);
      }
    }
    

  	public function executeOld($request)
    {

      // create our logger object
      $logger = new sfFileLogger(new sfEventDispatcher(), array('file' => sfConfig::get('sf_log_dir') . '/paypal_ipn.log'));
       
      // initialize the logger and set the file we want to log to
      //$logger->initialize(array('file' => SF_ROOT_DIR . '/log/paypal_ipn.log'));
       

      // read the post from PayPal system and add 'cmd'
      $req = 'cmd=_notify-validate';

      foreach ($request->getPostParameters() as $key => $value)
      {
        $value = urlencode(stripslashes($value));
        $req .= "&$key=$value";
      }

      foreach ($request->getGetParameters() as $key => $value)
      {
        $value = urlencode(stripslashes($value));
        $req .= "&$key=$value";
      }

      $logger->log($req, 0, "Payment");


      // post back to PayPal system to validate
      $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
      $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
      $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
      $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

      // assign posted variables to local variables
      $item_name = $request->getParameter('item_name');
      $item_number = $request->getParameter('item_number');
      $payment_status = $request->getParameter('payment_status');
      $payment_amount = $request->getParameter('mc_gross');
      $payment_currency = $request->getParameter('mc_currency');
      $txn_id = $request->getParameter('txn_id');
      $receiver_email = $request->getParameter('receiver_email');
      $payer_email = $request->getParameter('payer_email');
      $custom = $request->getParameter('custom');
      $first_name = $request->getParameter('first_name');
      $last_name = $request->getParameter('last_name');
      $mc_gross = $request->getParameter('mc_gross');

      $result = '';

      if (!$fp)
      {
        $logger->log('Callback PAYPAL FSOCKET ERROR', 0, "Payment");
      }
      else
      {
        fputs ($fp, $header . $req);
        while (!feof($fp))
        {
          $res = fgets ($fp, 1024);
          if (strcmp ($res, "VERIFIED") == 0)
          {
            // check the payment_status is Completed
            // check that txn_id has not been previously processed
            // check that receiver_email is your Primary PayPal email
            // check that payment_amount/payment_currency are correct
            // process payment

            $options = array();
            parse_str($custom, $options);
            if(isset($options['reservation_id']) && isset($options['ref_code']))
            {
              $reservation = Doctrine_Core::getTable('AoiItineraryReservation')
                                  ->createQuery('r')
                                  ->where('r.id = ?', $options['reservation_id'])
                                  ->andWhere('r.ref_code = ?', $options['ref_code'])
                                  ->fetchOne();
              if($reservation)
              {
                $currency = $reservation->getCurrency();

                $payment = new AoiPayment();
                $payment->setCustomerEmail($payer_email);
                $payment->setCustomerFirstname($first_name);
                $payment->setCustomerLastname($last_name);
                $payment->setStatus('validated');
                $payment->setCurrency($currency);
                $payment->setAmount($mc_gross);
                $payment->setReservationId($reservation->getId());
                $payment->save();

                if($mc_gross >= $reservation->getAmount())
                {
                  $reservation->setStatus('validated');
                  $reservation->save();
                }
              }
            }

            $logger->log('Callback VERIFIED VALID Receiver = '.$receiver_email.', payer =  '.$payer_email, 0, "Payment");

          }
          else if (strcmp ($res, "INVALID") == 0)
          {
            $logger->log('Callback VERIFIED INVALID Receiver = '.$receiver_email.', payer =  '.$payer_email, 0, "Payment");
          }
        }
        fclose ($fp);
      }

  		$this->setLayout(false);
  	}
  }